package com.jq.jqaicode.ai.workflow.notes;

import com.jq.jqaicode.config.ThreadPoolConfig;
import com.jq.jqaicode.common.file.CodeParserSaveExecutor;
import com.jq.jqaicode.common.file.VueCodeParserSave;
import com.jq.jqaicode.model.enums.CodeGenTypeEnum;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.UserMessage;
import org.bsc.langgraph4j.action.NodeAction;
import org.bsc.langgraph4j.langchain4j.generators.StreamingChatGenerator;
import org.bsc.langgraph4j.prebuilt.MessagesState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 打包部署
 */
@Component
public class VueBuildNode implements NodeAction<MessagesState<ChatMessage>> {

    @Autowired
    @Qualifier(ThreadPoolConfig.DEFAULT_EXECUTOR)
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public Map<String, Object> apply(MessagesState<ChatMessage> chatMessageMessagesState) throws Exception {
        StreamingChatGenerator<MessagesState<ChatMessage>> generator = StreamingChatGenerator.<MessagesState<ChatMessage>>builder()
                .mapResult(response -> Map.of("messages", response.aiMessage()))
                .startingNode("vueBuildNode")
                .startingState(chatMessageMessagesState)
                .build();

        //获取ai生成的code
        AiMessage chatMessage = (AiMessage)chatMessageMessagesState.lastMessage()
                .orElseThrow(() -> (new IllegalStateException("last message not found!")));

        //获取用户提交的appId
        UserMessage userMessage = (UserMessage)chatMessageMessagesState.lastMinus(1).orElseThrow(() -> (new IllegalStateException("last message not found!")));;
        String appId=userMessage.name();

        //生成文件
        CodeParserSaveExecutor.executeParser(appId, chatMessage.text(), CodeGenTypeEnum.VUE_FILE);

        //打包部署
        //threadPoolTaskExecutor.execute(() -> {
            VueCodeParserSave.build(appId);
        //});

        return Map.of("_streaming_messages", "No greeting found.");
    }
}
